package com.work.straighttalk.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.PathUtil;
import com.rockerhieu.emojicon.EmojiconEditText;
import com.rockerhieu.emojicon.EmojiconGridFragment;
import com.rockerhieu.emojicon.EmojiconsFragment;
import com.rockerhieu.emojicon.emoji.Emojicon;
import com.work.straighttalk.R;
import com.work.straighttalk.adapter.ChatRVAdapter;
import com.work.straighttalk.adapter.OnRecyclerViewClickListener;
import com.work.straighttalk.adapter.OnVoicePlayerListener;
import com.work.straighttalk.adapter.SendVoiceHolder;
import com.work.straighttalk.app.BaseActivity;
import com.work.straighttalk.bean.StraightTalkMessage;
import com.work.straighttalk.presenter.ChatPImpl;
import com.work.straighttalk.presenter.i.ChatPI;
import com.work.straighttalk.ui.i.ChatVI;
import com.work.straighttalk.utils.CommonUtils;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by dllo on 16/3/4.
 */
public class ChatActivity extends BaseActivity implements ChatVI<StraightTalkMessage>, OnRecyclerViewClickListener, EMMessageListener, View.OnTouchListener, OnVoicePlayerListener, EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {

    private static final int REQUEST_CODE_LOCAL = 3;
    private static final int REQUEST_CODE_CONTACT = 6;
    private static final int REQUEST_CODE_CONTACT_MES = 7;
    private static final int REQUEST_CODE_CAMERA = 2;
    @Bind(R.id.ic_back)
    ImageView icBack;
    @Bind(R.id.ic_avatar)
    SimpleDraweeView icAvatar;
    @Bind(R.id.ic_action_call)
    RelativeLayout icActionCall;
    @Bind(R.id.ic_action_attach)
    RelativeLayout icActionAttach;
    @Bind(R.id.ic_more_shadow)
    RelativeLayout icMoreShadow;
    @Bind(R.id.ic_menu)
    LinearLayout icMenu;
    @Bind(R.id.tv_username)
    TextView tvUsername;
    @Bind(R.id.last_login_time)
    TextView lastLoginTime;
    @Bind(R.id.chat_bar)
    RelativeLayout chatBar;
    @Bind(R.id.att_audio)
    ImageView attAudio;
    @Bind(R.id.layout_audio)
    LinearLayout layoutAudio;
    @Bind(R.id.att_document)
    ImageView attDocument;
    @Bind(R.id.layout_doc)
    LinearLayout layoutDoc;
    @Bind(R.id.layout_group1)
    RelativeLayout layoutGroup1;
    @Bind(R.id.attach_camera)
    ImageView attachCamera;
    @Bind(R.id.layout_camera)
    LinearLayout layoutCamera;
    @Bind(R.id.att_location)
    ImageView attLocation;
    @Bind(R.id.layout_group2)
    RelativeLayout layoutGroup2;
    @Bind(R.id.att_gallery)
    ImageView attGallery;
    @Bind(R.id.layout_gallery)
    LinearLayout layoutGallery;
    @Bind(R.id.att_contact)
    ImageView attContact;
    @Bind(R.id.layout_group)
    RelativeLayout layoutGroup;
    @Bind(R.id.attach_layout)
    LinearLayout attachLayout;
    @Bind(R.id.rv_chat)
    RecyclerView rvChat;
    @Bind(R.id.btn_chat_send)
    ImageButton btnChatSend;
    @Bind(R.id.imbtn_chat_send)
    ImageButton imbtnChatSend;
    @Bind(R.id.btn)
    FrameLayout btn;
    @Bind(R.id.input_emoji)
    ImageView inputEmoji;
    @Bind(R.id.input_kbd)
    ImageView inputKbd;
    @Bind(R.id.et_content)
    EmojiconEditText etContent;
    @Bind(R.id.input_cam)
    ImageView inputCam;
    @Bind(R.id.ex_layout)
    FrameLayout exLayout;

    private ChatRVAdapter chatRVAdapter;
    private ChatPI chatPI;
    private String userID = "";
    private LinearLayoutManager manager;
    private boolean isShowing = false;
    private File cameraFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        /***
         * 用于监听输入
         */
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etContent.getText().toString())) {
                    btnChatSend.setVisibility(View.INVISIBLE);
                    imbtnChatSend.setVisibility(View.VISIBLE);
                    inputCam.setVisibility(View.VISIBLE);
                } else {
                    btnChatSend.setVisibility(View.VISIBLE);
                    imbtnChatSend.setVisibility(View.INVISIBLE);
                    inputCam.setVisibility(View.INVISIBLE);
                }
            }
        });
        attachLayout.bringToFront();
        setEmojiconFragment(false);
        imbtnChatSend.setOnTouchListener(this);
        Intent intent = getIntent();
        userID = intent.getStringExtra("userID");
        chatRVAdapter = new ChatRVAdapter();
        manager = new LinearLayoutManager(this);
        manager.setStackFromEnd(true);
        rvChat.setLayoutManager(manager);
        rvChat.setAdapter(chatRVAdapter);
        chatRVAdapter.setListener(this);
        chatRVAdapter.setVoicePlayerListener(this);
        chatPI = new ChatPImpl(this);
        chatPI.loadData();
        EMClient.getInstance().chatManager().addMessageListener(this);
    }

    @OnClick(R.id.btn_chat_send)
    protected void sendMessage() {
        chatPI.sendTextMessage(etContent.getText().toString());
    }
//---

    /**
     * 显示attach 栏
     */
    @OnClick(R.id.ic_action_attach)
    protected void showAttach() {
        if (isShowing) {
            attachLayout.setVisibility(View.INVISIBLE);
            isShowing = false;
        } else {
            attachLayout.setVisibility(View.VISIBLE);
            isShowing = true;
        }
    }

    /**
     * attach 栏 手机联系人页面
     */
    @OnClick(R.id.att_contact)
    protected void chosePhoneContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        ChatActivity.this.startActivityForResult(intent, REQUEST_CODE_CONTACT);
        attachLayout.setVisibility(View.INVISIBLE);
    }

    @OnClick(R.id.att_location)
    protected void toLocation() {
        Intent intent = new Intent(this, LocationActivity.class);
        startActivity(intent);
    }

    /**
     * 加载Emojifragment
     *
     * @param useSystemDefault
     */
    private void setEmojiconFragment(boolean useSystemDefault) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.ex_layout, EmojiconsFragment.newInstance(useSystemDefault))
                .commit();
    }

    /**
     * 笑脸按钮 显示emoji 栏
     */
    @OnClick(R.id.input_emoji)
    protected void showEmoji() {
        exLayout.setVisibility(View.VISIBLE);
        inputEmoji.setVisibility(View.GONE);
        inputKbd.setVisibility(View.VISIBLE);
    }

    /**
     * 键盘 显示 输入法
     */
    @OnClick(R.id.input_kbd)
    protected void showKBD() {
        exLayout.setVisibility(View.GONE);
        inputEmoji.setVisibility(View.VISIBLE);
        inputKbd.setVisibility(View.GONE);
    }

    @Override
    public void loadItems(List<StraightTalkMessage> lists) {
        chatRVAdapter.loadData(lists);
    }


    @Override
    public void showItemLoading(StraightTalkMessage itemData) {
        chatRVAdapter.addData(itemData);
    }

    /**
     * message 刷新
     */
    @Override
    public void addItem(StraightTalkMessage emMessage) {
        chatRVAdapter.addData(emMessage);
    }

    @Override
    public void setEditTextNull() {
        etContent.setText("");
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    /**
     * chat 携带的聊天对象ID 获取
     *
     * @return
     */
    @Override
    public String getID() {
        return userID;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_CONTACT:
                Bundle bundle = new Bundle();
                bundle.putParcelable("ContactUri", data.getData());
                startActivityForResult(ContactsMesEditorActivity.class, bundle, REQUEST_CODE_CONTACT_MES);
                break;
            case REQUEST_CODE_LOCAL:
                Uri selectedImage = data.getData();
                Log.d("ddd", selectedImage.toString());
                chatPI.sendPicByUri(selectedImage);
//                sendPicByUri(selectedImage);
                break;
            case REQUEST_CODE_CONTACT_MES:

                break;
            case REQUEST_CODE_CAMERA:
                if (cameraFile != null && cameraFile.exists())
                    toast(cameraFile.getAbsoluteFile());
                break;
            default:
                break;
        }

    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */


    /**
     * 当自己输入信息的时候 移到底部
     */
    @Override
    public void toBottom() {
        rvChat.smoothScrollToPosition(chatRVAdapter.getItemCount());
    }

    @Override
    public void showSeekBarProgress(String msgID, int progress) {
        int position = chatRVAdapter.getItemByID(msgID);
        View view = manager.findViewByPosition(position);
        SendVoiceHolder holder = (SendVoiceHolder) rvChat.getChildViewHolder(view);
        holder.setSeekBarProgress(progress);
    }

    @Override
    public void showSeekBarMax(String msgID, int max) {
        int position = chatRVAdapter.getItemByID(msgID);
        View view = manager.findViewByPosition(position);
        SendVoiceHolder holder = (SendVoiceHolder) rvChat.getChildViewHolder(view);
        holder.setSeekBarMax(max);
    }

    @Override
    protected void onDestroy() {
        EMClient.getInstance().chatManager().removeMessageListener(this);
        super.onDestroy();
    }


    @Override
    public void onRecyclerViewCLick(Object o) {
    }


    /**
     * 收到消息
     *
     * @param list
     */
    @Override
    public void onMessageReceived(List<EMMessage> list) {
        for (EMMessage message : list) {
            String username = null;
            // 群组消息
            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // 单聊消息
                username = message.getFrom();
            }

            // 如果是当前会话的消息，刷新聊天页面
            if (username.equals(userID)) {
//                messageList.refreshSelectLast();
                // 声音和震动提示有新消息
                chatPI.loadData();
            } else {
                // 如果消息不是和当前聊天ID的消息
                //TODO 新消息来到时 通知栏

            }
        }
    }

    /**
     * 收到透传消息
     *
     * @param list
     */
    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    /**
     * 收到已读回执
     *
     * @param list
     */
    @Override
    public void onMessageReadAckReceived(List<EMMessage> list) {

    }

    /**
     * @param list
     */
    @Override
    public void onMessageDeliveryAckReceived(List<EMMessage> list) {
    }

    /**
     * 消息状态变动的 监听
     *
     * @param emMessage
     * @param o
     */
    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {
        chatPI.loadData();
    }

    /**
     * 录音按钮的 onTouch 事件监听
     *
     * @param v
     * @param event
     * @return
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                chatPI.recordVoice();
                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:
                if (event.getY() < 0) {
                    chatPI.discordVoice();
                } else {
                    chatPI.sendVoiceMessage();
                }
                break;
        }
        return false;
    }

    @Override
    public void voicePlay(StraightTalkMessage message) {
        chatPI.startPlayer(message);
    }

    @Override
    public void voicePause() {
        chatPI.pausePlayer();
    }

    @Override
    public void seekTo(int progress) {
        chatPI.seekTo(progress);
    }

    @Override
    public void onEmojiconBackspaceClicked(View v) {
        EmojiconsFragment.backspace(etContent);
    }

    @Override
    public void onEmojiconClicked(Emojicon emojicon) {
        EmojiconsFragment.input(etContent, emojicon);
    }

    /**
     * 从图库获取图片
     */
    @OnClick(R.id.att_gallery)
    protected void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    /**
     * 照相机获取图片
     */
    @OnClick(R.id.attach_camera)
    protected void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            Toast.makeText(getActivity(), R.string.sd_card_not_found, Toast.LENGTH_SHORT).show();
            return;
        }
        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMClient.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }
}